import { defineStore } from "pinia";
import { getMenu } from '@/api/modules/login';
import type { Router } from 'vue-router';
import ErrComp from '@/views/Err.vue';
interface UserState {
  userInfo:UserInfo
  userMenu: UserMenu[]
}
const componentMap: Record<string, () => Promise<any>> = {
  '/home/accomUser': () => import('@/views/wish/index.vue'),
  '/home/order': () => import('@/views/account/index.vue'),
  '/home/system': () => import('@/views/system/index.vue')
  // 添加你的所有组件...
};
export const useUserStore = defineStore('userStore', {
  // defineStore('userInfo',{})  userInfo就是这个仓库的名称name
  state: ():UserState => ({
    userInfo: {
      base64: null,
      chinaname: null,
      email: null,
      id: 0,
      isadmin: false,
      money: null,
      name: '',
      qqnumber: null,
      officium: null,
      roleListCode: null,
      roleListName: null,
      roles: null,
    },
    userMenu: []
  }),
  actions: {
    setUserInfos(users: UserInfo) {
      Object.assign(this.userInfo, users);
    },
    clearUserInfo(router:Router) {
      const needClearRoutes = router.getRoutes().filter(item => !item.meta.isCustomRouter);
      needClearRoutes.forEach((item)=>{
        router.removeRoute(item.name!)
      })
      this.userInfo = {
        base64: null,
        chinaname: null,
        email: null,
        id: 0,
        isadmin: false,
        money: null,
        name: '',
        qqnumber: null,
        officium: null,
        roleListCode: null,
        roleListName: null,
        roles: null
      }
      this.userMenu = [];
    },
    filterMenu(auth: string | null) {
      const roles = this.userInfo.roleListCode ?? '';
      const roleArray = !!roles ? roles.split(',') : [];
      const authArray = !!auth ? auth.split(',') : [];
      if (authArray.length === 0) {
        return true;
      }
      let flag = false;
      for (let i = 0; i < authArray.length; i++) {
        if (roleArray.includes(authArray[i])) {
          flag = true;
        }
      }
      return flag;
    },
    // 生成菜单
    async generateMenu(router: Router) {
      try {
        const res: any = await getMenu();
        if (res.code !== 200) throw new Error(res.message);
        const arrayList = res.data.filter((item: UserMenu) => {
          return this.filterMenu(item.auth) && item.show === '1' && item.adaptability === '4'
        }).map((parent: any) => {
          return {
            ...parent,
            children: parent.children.filter((child: UserMenu) => {
              return this.filterMenu(child.auth) && child.show === '1' && child.adaptability === '4'
            })
          }
        });
        if (arrayList && arrayList.length > 0 && arrayList[0].children) {
          this.userMenu = [];
          // 在 generateMenu 方法中修改
          (arrayList[0].children ?? []).forEach((menu: UserMenu) => {
            this.userMenu.push(menu);
            // 确保路径格式正确
            router.addRoute('home', {
              path: menu.path,
              component: componentMap[menu.path] ?? ErrComp,
              name: menu.title
            });
          });
        }
      } catch (error) {
        console.log(error);
      }
    }
  },
  getters: {
    hasLogin: state => Boolean(state.userInfo.id),
    avatar: state => state.userInfo.base64,
    chineseName: state => state.userInfo.chinaname,
  }
})